package com.banmao.mall.controller.client;

import com.banmao.mall.model.bo.client.address.AddressDetailBO;
import com.banmao.mall.model.vo.BaseRespVO;
import com.banmao.mall.model.vo.client.address.AddressBaseVO;
import com.banmao.mall.model.vo.client.address.AddressDetailVO;
import com.banmao.mall.model.vo.client.address.RegionVO;
import com.banmao.mall.service.client.AddressSercice;
import com.banmao.mall.util.CustomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController("cAddressController")
@RequestMapping("/wx")
public class AddressController {

    @Autowired
    AddressSercice addressSercice;

    // 获取当前用户的地址列表
    @RequestMapping("/address/list")
    public BaseRespVO addressList() throws IllegalAccessException {

        Integer userId = CustomUtils.judgeUserLogin();

        List<AddressBaseVO> addressBaseVOS = addressSercice.addressList(userId);

        return BaseRespVO.ok(addressBaseVOS);
    }


    // 获取地址的详细信息
    @RequestMapping("/address/detail")
    public BaseRespVO addressDetail(@RequestParam("id") Integer addressId) throws IllegalAccessException {

        Integer userId = CustomUtils.judgeUserLogin();

        AddressDetailVO addressDetailVO = addressSercice.addressDetail(addressId);

        return BaseRespVO.ok(addressDetailVO);
    }

    // 保存地址
    @RequestMapping("/address/save")
    public BaseRespVO addressSave(@RequestBody @Validated AddressDetailBO addressDetailBO) throws IllegalAccessException {

        Integer userId = CustomUtils.judgeUserLogin();

        addressDetailBO.setUserId(userId);

        int result = 0;
        try {
            result = addressSercice.addressSave(addressDetailBO);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseRespVO.error("保存失败啦！", 401);
        }

        return BaseRespVO.ok(result);
    }


    // 获取地址信息中的地区列表
    @RequestMapping("/region/list")
    public BaseRespVO regionList(@RequestParam("pid") Integer pid) {

        List<RegionVO> regionVOS = addressSercice.regionList(pid);

        return BaseRespVO.ok(regionVOS);
    }


    // 删除地址信息（逻辑删除）
    @RequestMapping("/address/delete")
    public BaseRespVO addressDelete(@RequestBody Map<String, Integer> map) throws IllegalAccessException {

        // 验证登陆，否则不能删除
        Integer integer = CustomUtils.judgeUserLogin();

        Integer id = map.get("id");
        int result = addressSercice.addressDelete(id);
        if(result == 0) {
            return BaseRespVO.error("删除失败~", 401);
        }

        return BaseRespVO.ok(null);
    }

}
